<template>
    <div class="minW1060-auto bg-fff mt10">
        <div class="pad20 ml10">
            <!--搜索条件-->
            <el-row>
                    <div class="dlblock-mb20">
                        <span class="pr5 ml10">角色名称</span>
                        <el-input v-model.trim="param.name" size="medium" @keydown.enter.native="getRolesFn"
                                  placeholder="角色名称" style="width: 150px;"
                                  :maxlength="10"
                                  show-word-limit clearable>
                        </el-input>
                    </div>
                    <div class="dlblock-mb20 pr5 pl5">
                        <el-button
                                @click="param.page = 1,getRolesFn()"
                                class="el-icon-search ml5"
                                circle
                        ></el-button>
                    </div>
                        <div class="dlblock-mb20 pr5 pl5">
                            <!--<router-link :to="{path:'role/edit',query:{menuName:'添加角色'}}">
                                <el-button type="primary">添加</el-button>
                            </router-link>-->
                            <el-button type="primary" @click="editBtn(1)">添加</el-button>
                        </div>
                        <!--<div class="dlblock-mb20 pr10">
                            <el-button type="danger" @click="delRolesFn">删除</el-button>
                        </div>-->
            </el-row>
            <!--表格-->
            <el-row>
                <el-table class="my-table"
                          :data="roleList" stripe
                          v-loading="loading"
                          :header-row-class-name="'my-table-header'"
                          @selection-change="handleSelectionChange"
                          ref="myTable"
                          border>
                    <el-table-column align="center" prop="name" label="角色名称">
                    </el-table-column>
                    <el-table-column align="center" prop="memberCount" label="成员角色数">
                    </el-table-column>
                    <el-table-column align="center" prop="inherits" label="传播标志">
                    </el-table-column>
                    <el-table-column align="center" prop="disabled" label="是否禁用">
                        <template slot-scope="{row}">
                            {{row.disabled==0?"未禁用":"禁用"}}
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="creationTime" :formatter="dataYear" label="创建时间">
                    </el-table-column>
                    <el-table-column align="center" prop="remarks" label="备注">
                        <template slot-scope="{row}">
                            {{row.remarks}}
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="操作" fixed="right">
                        <template slot-scope="{row}">
                            <!--<router-link :to="{path:'role/edit', query:{role:row,menuName:'编辑角色'}}">
                                <el-button type="text">编辑</el-button>
                            </router-link>&nbsp;-->
                            <el-button type="text" @click="editBtn(2,row)">编辑</el-button>
                            <el-button type="text" style="color: #f56c6c" @click="delRoleFn(row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
            <!--分页控件-->
            <el-row :gutter="20" class="mt10">
                <el-col :span="12" :offset="6" align="center">
                    <el-pagination background layout="total, prev, pager, next" :total="param.total"
                                   :page-size="param.size"
                                   :current-page="param.page" @current-change="pageChange">
                    </el-pagination>
                </el-col>
            </el-row>

            <!--编辑角色-->
            <el-dialog :title="`编辑角色-${editData.add ==1 ? '添加' :'编辑'}`" :visible.sync="editData.modal" width="1000px" :close-on-click-modal="false" v-dialogDrag>
                <div class="pad20 mt10">
                    <el-form label-position="left" label-width="80px" ref="baseform" v-model="role">
                        <!--基本信息-->
                        <el-row>
                            <el-col align="left">
                                <h1>基本信息</h1>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="7">
                                <div class="dlblock-mb20 mt40 mb30 ml20">
                                    <el-form-item label="角色名称" prop="name">
                                        <el-input v-model.trim="role.name" size="medium"
                                                  placeholder="角色名称" style="width: 150px;"
                                                  :maxlength="10"
                                                  show-word-limit clearable required>
                                        </el-input>
                                    </el-form-item>
                                </div>

                            </el-col>
                            <el-col :span="9">
                                <div class="dlblock-mb20 mt40 mb30">
                                    <el-form-item label="备注" prop="remark">
                                        <el-input v-model.trim="role.remarks" size="medium"
                                                  placeholder="备注" style="width: 240px;"
                                                  :maxlength="20"
                                                  show-word-limit clearable>
                                        </el-input>
                                    </el-form-item>
                                </div>
                            </el-col>
                            <el-col :span="7">
                                <div class="dlblock-mb20 mt50 mb30">
                                    <label class="mr20">状态</label>
                                    <el-radio-group v-model="role.disabled">
                                        <el-radio :label="0">已启用</el-radio>
                                        <el-radio :label="1">已禁用</el-radio>
                                    </el-radio-group>
                                </div>
                            </el-col>
                        </el-row>
                    </el-form>
                    <el-row>
                        <el-col :span="16">
                            <!--平台权限-->
                            <el-row>
                                <el-col align="left">
                                    <h1>平台权限</h1>
                                </el-col>
                            </el-row>
                            <el-row class="mt20">
                                <el-col :span="24" :push="1">
                                    <el-transfer
                                            @change="getFunctionTreeFn(1, $event)"
                                            :titles="['未选平台', '已选平台']"
                                            v-model="checkPlatformList"
                                            :data="platformList"
                                            :props="{ key: 'objectId', label: 'objectName' }">
                                    </el-transfer>
                                </el-col>
                            </el-row>
                        </el-col>
                        <el-col :span="16">
                            <!--账号角色-->
                            <el-row>
                                <el-col align="left">
                                    <h1>账号角色</h1>
                                </el-col>
                            </el-row>
                            <el-row class="mt20">
                                <el-col :span="24" :push="1">
                                    <el-transfer
                                            filterable
                                            :titles="['未选账号', '已选账号']"
                                            v-model="checkAccountList"
                                            :data="accountList"
                                            :props="{ key: 'id', label: 'loginId' ,disabled: 'disabled'}">
                                    </el-transfer>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                    <!--权限分配-->
                    <el-row>
                        <el-col align="left">
                            <h1>权限分配</h1>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" :push="1">
                            <div class="function-box" height="250">
                                <el-tree ref="functionTree" :data="functionTree" show-checkbox node-key="id"
                                         :props="{ label: 'name', children: 'items'}">
                                </el-tree>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col  align="center">
                            <div class="dlblock-mb20 pr10 ml20">
                                <el-button type="primary" @click="savaRoleFn">保存</el-button>
                            </div>
                            <div class="dlblock-mb20 pr10">
                                <el-button type="danger" @click="setFunctionTree">重置</el-button>
                            </div>
                        </el-col>
                    </el-row>

                </div>

            </el-dialog>
        </div>
    </div>
</template>

<script>
    import {getRoles, delRole,getUserDataByToken,addRole,getPlatformIds,getMenuIds,updateRole,getAdminNoRoleInfo} from "@/api"
    import {myDate} from "../../../../utils/common";

    export default {
        name: "index",
        components: {},
        data() {
            return {
                /*==========公用变量=========*/
                // 必填项提醒
                required: {
                    required: true,
                    message: '此输入框必填',
                    trigger: 'blur'
                },
                // 加载过渡动画
                loading: false,
                param: {
                    name: '',
                    offset: 0,
                    count: 10,
                    visible: 0,
                    total: 0,
                    size: 15,
                    page: 1
                },
                group: '',
                // 分组树
                groupTree: [],
                roleList: [],
                roleIds: [],
                pages: {
                    page: 1,
                    total: 0,
                    size: 10
                },
                editData: {
                    modal:false,
                    add:1,
                },
                role: {
                    name: '',
                    remarks: '',
                    disabled: '',
                },
                checkAccountList:[],
                accountList:[],
                checkPlatformList:[],
                platformList: [
                    /*{
                        "objectId": 1,
                        "objectName": "基础数据系统"
                    },
                    {
                        "objectId": 2,
                        "objectName": "运营管理系统"
                    },
                    {
                        "objectId": 3,
                        "objectName": "客流统计系统"
                    },*/
                    {
                        "objectId": 4,
                        "objectName": "视频监控系统"
                    },
                    {
                        "objectId": 5,
                        "objectName": "出租车系统"
                    },
                ],
                functionTree: [],
                mainMenu: {
                    "items": [],
                    "href": "",
                    "html": '',
                    "id": '',
                    "name": "",
                    "parentId": '',
                    "qualifiedName": "",
                    "title": "el-icon-sunrise-1",
                    "value": ''
                },
                savaFlag: 0,
            }
        },
        created() {
            this.getRolesFn();
        },
         methods: {
             setFunctionTree() {
                 this.$refs.functionTree.setCheckedKeys(this.menuIdsP)
             },
             // 保存角色
             savaRoleFn() {
                 this.loading = true
                 let platformIds = this.checkPlatformList
                 let menuIds = this.$refs.functionTree.getCheckedKeys();
                 if (this.savaFlag) {
                     this.updateRoleFn(platformIds, menuIds)
                     this.editData.modal=false
                     this.getRolesFn();
                 } else {
                     this.addRoleFn(platformIds, menuIds)
                     this.editData.modal=false
                     this.getRolesFn();
                 }
             },
             async editBtn(t,row){
                if (t==1){
                    this.editData.modal=true;
                    this.role.disabled=''
                    this.role.remarks=''
                    this.role.name=''
                    this.checkPlatformList=[]
                    this.checkAccountList=[]
                    this.getFunctionTreeFn(1, []);
                    // 获取未绑定当前角色的账号集合
                    await getAdminNoRoleInfo({id: 0}).then(res => {
                        if (res != null && res.code == 200) {
                            this.accountList = res.data
                        }
                    })
                }else {
                    this.savaFlag = 1
                    this.editData.modal=true
                    //编辑信息
                    this.role = row
                    //已有成员
                    this.checkAccountList = this.role.accounts
                    // 获取该角色所拥有的系统信息 已选平台
                    var roles = []
                    if (this.role.members instanceof Array) {
                        roles = this.role.members
                        roles.push(this.role.id)
                    } else {
                        roles[0] = this.role.id
                    }
                    // 获取未绑定当前角色的账号集合
                    await getAdminNoRoleInfo({id: row.id}).then(res => {
                        if (res != null && res.code == 200) {
                            this.accountList = res.data
                        }
                    })
                    // 获取已经拥有的菜单集合
                    await getMenuIds({roleIds: roles}).then(res => {
                        if (res != null && res.code == 200) {
                            this.menuIdsP = res.data
                        }
                    })
                    // 获取已经拥有的平台集合
                    await getPlatformIds({roleIds: roles}).then(res => {
                        if (res != null && res.code == 200) {
                            this.checkPlatformList = res.data
                            // 获取functionTree值
                            this.getFunctionTreeFn(2, this.checkPlatformList)
                        }
                    })

                }
            },

             getName(type) {
                 switch (type) {
                     /*case 1: {
                         return '基础数据系统'
                     }
                     case 2: {
                         return '运营管理系统'
                     }
                     case 3: {
                         return '客流统计系统'
                     }*/
                     case 4: {
                         return '视频监控系统'
                     }
                     case 5:
                         return '出租车系统';
                     default:
                         break;
                 }
                 return undefined;
             },
             async getFunctionTreeFn(t, val) {
                if (!val.length) {
                    this.functionTree = [];
                    return 0;
                }
                this.functionTree = []
                for (let i = 0; i < val.length; i++) {
                    let mainMenu = JSON.parse(JSON.stringify(this.mainMenu))
                    mainMenu.name = this.getName(val[i])
                    mainMenu.id = val[i]
                    await getUserDataByToken({
                        type: val[i]
                    }).then(res => {
                        mainMenu.items = res.data
                        this.functionTree.push(mainMenu)
                        if (t == 2) {
                        }
                    })
                }
                this.$refs.functionTree.setCheckedKeys(this.menuIdsP)
            },

             addRoleFn(platformIds, menuIds) {
                 console.log(this.checkAccountList)
                 addRole({
                     roleName: this.role.name,
                     members: this.checkAccountList,
                     remarks: this.role.remarks,
                     disabled: this.role.disabled,
                     platformIds,
                     menuIds,

                 }).then(res => {
                     if (res != null && res.code == 200) {
                         this.$message.success("添加成功")
                         //this.$router.push("/role")
                     }
                 }).finally(() => {
                     this.loading = false
                 })
             },
             updateRoleFn(platformIds, menuIds) {
                 updateRole({
                     roleName: this.role.name,
                     roleId: this.role.id,
                     members: this.checkAccountList,
                     remarks: this.role.remarks,
                     disabled: this.role.disabled,
                     platformIds,
                     menuIds,
                 }).then(res => {

                     if (res != null && res.code == 200) {
                         this.$message.success("更新成功")
                         //this.$router.push("/role")
                         //this.$store.dispatch('tagsView/delView', {path: '/role/edit'})
                     }
                 }).finally(() => {
                     this.loading = false
                 })
             },
            // 处理时间成 yyyy-MM-DD HH:ss:mm
            dataYear(row, column) {
                const daterc = row[column.property];
                let myDate1
                if (daterc != null) {
                    myDate1 = myDate(new Date(daterc));
                }
                return myDate1
            },
            checkMethod(event, index) {
                let e = event.target
                if (e.parentElement.classList.contains("is-checked")) {
                    e.parentElement.classList.remove("is-checked")
                    this.roleIds.splice(index - 1, 1)

                } else {
                    e.parentElement.classList.add("is-checked")
                    this.roleIds[index - 1] = this.roleList[index - 1].id
                }
                let checkeds = document.querySelectorAll(".mydeal");
                let b = 0
                checkeds.forEach(item => {
                    if (item.classList.contains("is-checked")) {
                        b = b + 1;
                    }
                })
                let els = document.querySelectorAll(".el-table-column--selection");
                if (b == this.roleList.length || b - 8 == this.roleList.length) { //全选
                    this.checkSwitch(els[11].querySelector(".el-checkbox__inner"))
                } else if (b < this.roleList.length || b - 8 < this.roleList.length) {
                    this.checkRemove(els[11].querySelector(".el-checkbox__inner"))
                }
            },
            // 表格多选
            handleSelectionChange(val) {
                this.roleIds = val.map(item => item.id)
                var els = document.querySelectorAll(".el-table-column--selection");
                let hasChecked = els[5].querySelector(".el-checkbox__inner").parentElement.classList.contains("is-checked")
                if (hasChecked) {
                    document.querySelectorAll(".el-checkbox__inner").forEach(el => {
                        this.checkRemove(el)
                    })
                } else {
                    document.querySelectorAll(".el-checkbox__inner").forEach(el => {
                        this.checkAdd(el)
                    })
                }
            },
            // 页码改变
            pageChange(page) {
                this.param.page = page;
                this.getRolesFn();
            },
            // 删除角色集合
            delRolesFn() {
                if (this.roleIds.length != 0) {
                    this.loading = true
                    try {
                        this.roleIds.forEach(id => {
                            delRole({
                                id: id,
                                recursive: true
                            })
                        })
                        this.$message.success('删除成功')
                    } catch (e) {
                        console.log(e)
                    } finally {
                        this.loading = false
                        this.getRolesFn()
                    }
                }
            },

            indexMethod(index) {
                return index + (this.param.page - 1) * 10 + 1;
            },

            // 删除角色
            delRoleFn(id) {
                this.loading = true
                delRole({
                    id: id,
                    recursive: true,
                    visible: 0,
                }).then(res => {
                    if (res != null && res.code == 200) {
                        if (res.data == 1) {
                            this.$message.success("删除成功")
                            this.getRolesFn()
                        } else {
                            this.$message.success(res.data.message)
                        }
                    }
                }).finally(() => {
                    this.loading = false
                })
            },
            // 获取角色集合
            getRolesFn() {
                this.loading = true
                getRoles(this.param).then(res => {
                    if (res != null && res.code == 200) {
                        if (res.data != null) {
                            this.roleList = res.data.list
                            this.param.total = res.data.count
                            this.index = (this.param.page - 1)
                        }
                    }
                }).finally(() => {
                    this.loading = false
                })
            },
            checkSwitch(e) {
                if (e.parentElement.classList.contains("is-checked")) {
                    e.parentElement.classList.remove("is-checked")
                } else {
                    e.parentElement.classList.add("is-checked")
                }
            },
            checkAdd(e) {
                e.parentElement.classList.add("is-checked")
            },
            checkRemove(e) {
                e.parentElement.classList.remove("is-checked")
            },
        }
    }
</script>

<style>
    span.checkbox {
        position: relative;
        left: 5px;
        top: -1px;
    }
    .my-table /deep/ tr, .my-table /deep/ td{
        padding: 0 !important;
        height: 40px;
        line-height: 40px;
    }
    .function-box {
        margin-top: 15px;
        width: 100%;
        height: 200px;

        border: 1px solid #ebeef5;
        overflow: auto;
    }
</style>
